﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LG_RECV_HEART
{
    public class ServiceLog
    {
        public static void Start()
        {
            Thread thread = new Thread(Init);
            thread.IsBackground = true;
            thread.Start();
        }
        private static void Init()
        {
            while (true)
            {
                try
                {
                    DeleteFile(System.Environment.CurrentDirectory + @"\\Logs\\", 7); //删除该⽬录下超过 7天的⽂件
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.Message, err.StackTrace);
                }
                finally
                {
                    Thread.Sleep(1000);
                }
            }
        }

        private static void DeleteFile(string fileDirect, int saveDay)
        {
            try
            {
                DateTime nowTime = DateTime.Now;
                string[] files = Directory.GetFiles(fileDirect, "*.log", SearchOption.AllDirectories);  //获取该⽬录下所有 .txt⽂件
                foreach (string file in files)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    TimeSpan t = DateTime.Now - fileInfo.CreationTime;  //当前时间减去⽂件创建时间
                    int day = t.Days;
                    if (day > saveDay)   //保存的时间，单位：天
                    {
                        if (IsOccupy(fileInfo.FullName)) //判断⽂件是否被占⽤
                        {
                            System.IO.File.Delete(fileInfo.FullName); //删除⽂件
                        }
                        else
                        {
                            Logger<string>.Info("⽂件被占⽤，⽆法操作!");
                        }
                    }
                }

            }
            catch (Exception err)
            {
                Logger<string>.Debug(err.Message);
            }
        }


        [DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);
        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
        /// <summary>
        /// 判断⽂件是否被占⽤
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private static bool IsOccupy(string file)
        {
            bool result = true; //默认状态此⽂件未被占⽤
            try
            {
                //string vFileName = @"c:\temp\temp.bmp";
                string vFileName = file;
                if (!System.IO.File.Exists(vFileName))
                {
                    //Logger.Info("⽂件都不存在!");
                    result = false;
                }
                IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE); if (vHandle == HFILE_ERROR)
                {
                    Logger<string>.Info("⽂件被占⽤！");
                    result = false;
                }
                CloseHandle(vHandle);
                Logger<string>.Info("没有被占⽤！");
            }
            catch (Exception err)
            {
                result = false;
                Logger<string>.Error(err.Message);
            }
            return result;
        }
    }
}
    


